package com.umeox.watch.audiobooks.ui

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.watch.audiobooks.R
import com.umeox.watch.audiobooks.bean.AudioBook
import com.umeox.watch.audiobooks.event.PlayStateEvent
import com.umeox.watch.audiobooks.utils.FAVORITE_LIST_REQUEST_CODE
import com.umeox.watch.audiobooks.utils.INTENT_KEY_AUDIO_ID
import com.umeox.watch.audiobooks.utils.INTENT_KEY_LIST_TYPE
import com.umeox.watch.audiobooks.utils.LIST_TYPE_ALL
import com.umeox.watch.audiobooks.utils.LIST_TYPE_FAVORITE
import com.umeox.watch.audiobooks.utils.LIST_TYPE_HOT
import com.umeox.watch.audiobooks.utils.SP_KEY_MUSIC_NAME
import com.umeox.watch.audiobooks.utils.StoryManager
import com.umeox.watch.audiobooks.utils.StoryManager.favoriteNameList
import com.umeox.watch.audiobooks.view.StoryProgressView
import com.umeox.watch.moto.dataservice.DataProvider
import com.yc.music.config.MusicConstant
import com.yc.music.inter.OnPlayerEventListener
import com.yc.music.model.AudioBean
import com.yc.music.service.PlayService
import com.yc.music.tool.BaseAppHelper
import com.yc.music.utils.MusicSpUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.util.Formatter
import java.util.Locale

class PlayingActivity : ThemeAppCompatActivity(), View.OnClickListener, OnPlayerEventListener {

    /**
     * 播放位置(秒)
     */
    private var playPosition = 0

    private var playListType = LIST_TYPE_ALL

    /**
     * 播放音频名称
     */
    private var playId = ""

    private var tvStoryName: TextView? = null
    private lateinit var sbProgress: StoryProgressView
    private var ivPrev: ImageView? = null
    private var ivPlay: ImageView? = null
    private var ivNext: ImageView? = null
    private var ivVolumeUp: ImageView? = null
    private var ivVolumeDown: ImageView? = null
    private var ivMusicList: ImageView? = null
    private var ivFavorite: ImageView? = null

    private var audioBean: AudioBean? = null

    private lateinit var mPlayServiceConnection: PlayServiceConnection
    private lateinit var mAudioManager: AudioManager
    private var mCurrentVolume: Int = 0
    private var mMaxVolume: Int = 0

    private var startPlayTime: Long = 0
    private var endPlayTime: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_playing)
        startCheckService(window.decorView)
        playPosition =
            MusicSpUtils.getInstance(MusicConstant.SP_NAME).getInt(MusicConstant.PLAY_POSITION, 0)

        if (playPosition < 1000) {
            playPosition = 0
        }
        playListType = intent.getIntExtra(INTENT_KEY_LIST_TYPE, LIST_TYPE_ALL)
        playId = intent.getStringExtra(INTENT_KEY_AUDIO_ID).toString()
        Logger.e("playName=$playId,playPosition=$playPosition")
        val playMode =
            MusicSpUtils.getInstance(MusicConstant.SP_NAME).getInt(MusicConstant.PLAY_MODE, 0)
        if(playMode != 0){
            MusicSpUtils.getInstance(MusicConstant.SP_NAME).put(MusicConstant.PLAY_MODE, 0)
        }

        initView()
        initPlayServiceListener()
        buildStoryData()
        initListener()
    }

    private fun initView() {
        tvStoryName = findViewById(R.id.tv_story_name)
        sbProgress = findViewById(R.id.story_pv)
        ivPrev = findViewById(R.id.iv_prev)
        ivPlay = findViewById(R.id.iv_play)
        ivNext = findViewById(R.id.iv_next)
        ivVolumeUp = findViewById(R.id.iv_volume_up)
        ivVolumeDown = findViewById(R.id.iv_volume_down)
        ivMusicList = findViewById(R.id.iv_music_list)
        ivFavorite = findViewById(R.id.iv_favorite)

        ivFavorite?.isSelected = favoriteNameList.contains(playId)

        setViewEnable(false)

        mAudioManager = getSystemService(AUDIO_SERVICE) as AudioManager
        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
    }

    private fun setViewEnable(enable: Boolean) {
        ivPlay?.isClickable = enable
        ivPrev?.isClickable = enable
        ivNext?.isClickable = enable
        sbProgress.isEnabled = enable
    }

    private fun initListener() {
        ivPlay?.setOnClickListener(this)
        ivPrev?.setOnClickListener(this)
        ivNext?.setOnClickListener(this)
        ivVolumeUp?.setOnClickListener(this)
        ivVolumeDown?.setOnClickListener(this)
        ivMusicList?.setOnClickListener(this)
        ivFavorite?.setOnClickListener(this)
    }

    @SuppressLint("SetTextI18n")
    private fun setViewData(playingMusic: AudioBean) {
        tvStoryName!!.text = playingMusic.title
//        tvStoryName!!.text = playingMusic.id

        sbProgress.setMax(playingMusic.duration.toFloat())
        sbProgress.setProgress(playPosition.toFloat())
    }

    private fun initPlayServiceListener() {
        if (BaseAppHelper.get().musicService == null) {
            return
        }
        BaseAppHelper.get().musicService.addOnPlayEventListener(this)
        val musicService = BaseAppHelper.get().musicService
        val playing = musicService.isPlaying
        ivPlay!!.isSelected = playing || musicService.isPreparing
    }

    override fun onResume() {
        super.onResume()
        ivFavorite?.isSelected = favoriteNameList.contains(playId)
    }


    override fun onDestroy() {
        super.onDestroy()
        if (::mPlayServiceConnection.isInitialized) {
            BaseAppHelper.get().musicService?.removeOnPlayEventListener(this)
        }
    }

    private fun onChangeImpl(music: AudioBean?) {
        Logger.e("============onChange music=${music}")
        if (music == null) {
            return
        }
        MusicSpUtils.getInstance(MusicConstant.SP_NAME).put(SP_KEY_MUSIC_NAME, music?.title ?: "")
        audioBean = music

        tvStoryName!!.text = music.title
//        tvStoryName!!.text = music.id

        sbProgress.setMax(music.duration.toFloat())
        sbProgress.setProgress(0f)
        ivFavorite?.isSelected = favoriteNameList.contains(music.id)
        ivPlay!!.isSelected =
            BaseAppHelper.get().musicService.isPlaying || BaseAppHelper.get().musicService.isPreparing
        EventBus.getDefault().post(PlayStateEvent())
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_play -> {
                BaseAppHelper.get().musicService?.playPause()
            }

            R.id.iv_next -> {
                val musicService = BaseAppHelper.get().musicService
                //切换下一首时需要判断上一首是否需要记录播放一次
                if (System.currentTimeMillis() - startPlayTime > 10 * 1000
                    && sbProgress.progress > 10 * 1000 && musicService?.isPlaying == true
                ) {
                    Logger.e("上一首播放已满足记录1次播放条件")
                    updateStoryPlayHistoryAmount()
                }
                musicService?.doNext()
            }

            R.id.iv_prev -> {
                val musicService = BaseAppHelper.get().musicService
                //切换下一首时需要判断上一首是否需要记录播放一次
                if (System.currentTimeMillis() - startPlayTime > 10 * 1000
                    && sbProgress.progress > 10 * 1000 && musicService?.isPlaying == true
                ) {
                    Logger.e("上一首播放已满足记录1次播放条件")
                    //TODO 更新数据库
                    updateStoryPlayHistoryAmount()
                }
                BaseAppHelper.get().musicService?.doPrev()
            }

            R.id.iv_volume_up -> {
                adjustVolume(true)
            }

            R.id.iv_volume_down -> {
                adjustVolume(false)
            }

            R.id.iv_favorite -> {
                ivFavorite?.setSelected(StoryManager.setFavorite(audioBean!!))
            }

            R.id.iv_music_list -> {
                startActivityForResult(
                    Intent(this, FavoriteActivity::class.java),
                    FAVORITE_LIST_REQUEST_CODE
                )
            }

            else -> {}
        }
    }

    private fun adjustVolume(up: Boolean) {
        mAudioManager.adjustStreamVolume(
            AudioManager.STREAM_MUSIC,
            if (up) AudioManager.ADJUST_RAISE else AudioManager.ADJUST_LOWER,
            0
        )
    }

    override fun onChange(music: AudioBean?) {
        onChangeImpl(music)
    }

    override fun onPlayerStart() {

        ivPlay!!.isSelected = true
//        if (first) {
//            BaseAppHelper.get().musicService.playPause()
//        }

        startPlayTime = System.currentTimeMillis()
        Logger.e("onPlayerStart=${startPlayTime}")
        EventBus.getDefault().post(PlayStateEvent())
    }

    override fun onPlayerPause() {

        ivPlay!!.isSelected = false
//        if (first) {
//            first = false
//            BaseAppHelper.get().musicService.seekTo(playPosition)
//        }
        endPlayTime = System.currentTimeMillis()
        Logger.e("(endPlayTime - startPlayTime)=${(endPlayTime - startPlayTime)},sbProgress.progress = ${sbProgress.progress}")
        if (endPlayTime - startPlayTime > 10 * 1000 && sbProgress.progress > 10 * 1000) {
            Logger.e("满足记录1次播放条件")
            updateStoryPlayHistoryAmount()
        }
        EventBus.getDefault().post(PlayStateEvent())
    }

    override fun onCompletion() {
        Logger.e("故事正常播放完成，更新对应故事播放次数+1")
        updateStoryPlayHistoryAmount()
    }

    private fun updateStoryPlayHistoryAmount() {
        var contentValues = DataProvider.getStoryPlayHistoryById(audioBean?.id!!.toLong())
        if (contentValues != null) {
            val dbAmountCount =
                contentValues.getAsInteger(DataProvider.StoryPlayHistoryProvider.AMOUNT)
            val id = contentValues.getAsInteger(DataProvider.StoryPlayHistoryProvider.ID)
            contentValues.put(DataProvider.StoryPlayHistoryProvider.AMOUNT, dbAmountCount + 1)
            val updateResult = DataProvider.updateStoryPlayHistory(
                contentValues,
                DataProvider.StoryPlayHistoryProvider.ID + "=?", arrayOf(id.toString())
            )
            Logger.e(if (updateResult > 0) "更新播放次数成功" else "更新播放次数失败")
        } else {
            contentValues = ContentValues()
            contentValues.put(DataProvider.StoryPlayHistoryProvider.ID, audioBean?.id!!.toLong())
            contentValues.put(DataProvider.StoryPlayHistoryProvider.AMOUNT, 1)
            val saveResult = DataProvider.saveStoryPlayHistory(contentValues)
            Logger.e(if (saveResult) "插入播放次数成功" else "插入播放次数失败")
        }

    }

    override fun onUpdateProgress(progress: Int) {
        val progressCompat = if (progress < 1000) {
            0
        } else {
            progress
        }
        sbProgress.setProgress(progressCompat.toFloat());
    }

    override fun onBufferingUpdate(percent: Int) {
    }

    override fun onTimer(remain: Long) {
    }

    override fun onDuration(totalDuration: Int) {
        sbProgress.setMax(totalDuration.toFloat())
    }

    /**
     * 检测服务
     */
    private fun startCheckService(rootView: View) {
        if (BaseAppHelper.get().playService == null) {
            startService()
        }

        rootView.postDelayed({ bindService() }, 500)
    }

    /**
     * 开启服务
     */
    private fun startService() {
        val intent = Intent(this, PlayService::class.java)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }

    /**
     * 绑定服务
     * 注意对于绑定服务一定要解绑
     */
    private fun bindService() {
        val intent = Intent()
        intent.setClass(mContext, PlayService::class.java)
        mPlayServiceConnection = PlayServiceConnection()
        mContext.bindService(intent, mPlayServiceConnection, Context.BIND_AUTO_CREATE)
    }

    /**
     * 构建数据集合
     */
    private fun buildStoryData() {

        for (bean in updateMusicList()) {
            if (bean.id == playId) {
                audioBean = bean
                setViewData(bean)
            }
        }
        Logger.e("audioBean1=" + audioBean.toString())

        if (audioBean == null) {
            audioBean = BaseAppHelper.get().musicList[0] as AudioBook
            setViewData(audioBean!!)
        }
        setViewEnable(true)
        val playService = BaseAppHelper.get().playService
        if (playService != null) {
            if (playService.isPlaying && playId == playService.playingMusic.id) {
                //点击了正在播放的这一曲
                sbProgress.setMax(playService.mediaPlayerTotalDuration.toFloat())
            } else {
                playService.play(BaseAppHelper.get().musicList.indexOf(audioBean))
            }
        }
    }

    private fun updateMusicList(): MutableList<AudioBean> {
        //初始化当前列表
        val list = when (playListType) {
            LIST_TYPE_ALL -> StoryManager.allStoryList
            LIST_TYPE_FAVORITE -> StoryManager.favoriteList
            LIST_TYPE_HOT -> StoryManager.hotStoryList
            else -> StoryManager.allStoryList
        }

        Logger.e("playListType=$playListType,size=${list.size}")


        val musicList = BaseAppHelper.get().musicList
        musicList.clear()
        musicList.addAll(list)
        return list
    }

    private fun formatTime(milliseconds: Long): String {
        if (milliseconds <= 0 || milliseconds >= 24 * 60 * 60 * 1000) {
            return "00:00"
        }
        val totalSeconds = milliseconds / 1000
        val seconds = totalSeconds % 60
        val minutes = totalSeconds / 60
        val hours = totalSeconds / 3600
        val stringBuilder = StringBuilder()
        val mFormatter = Formatter(stringBuilder, Locale.ENGLISH)
        return if (hours > 0) {
            mFormatter.format("%03d:%02d", minutes, seconds).toString()
        } else {
            mFormatter.format("%03d:%02d", minutes, seconds).toString()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == FAVORITE_LIST_REQUEST_CODE) {
            data?.let {
                playListType = it.getIntExtra(INTENT_KEY_LIST_TYPE, LIST_TYPE_FAVORITE)
                playId = it.getStringExtra(INTENT_KEY_AUDIO_ID).toString()

                for (bean in updateMusicList()) {
                    if (bean.id == playId) {
                        audioBean = bean
                        setViewData(bean)
                    }
                }
                val helper = BaseAppHelper.get()
                helper.playService.play(helper.musicList.indexOf(audioBean))
            }
        }
    }

    inner class PlayServiceConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            Logger.e("==========onServiceConnected==============")
            BaseAppHelper.get().playService = (service as PlayService.PlayBinder).service
            lifecycleScope.launch(Dispatchers.Main) {
                initPlayServiceListener()

                buildStoryData()
//                val playService = BaseAppHelper.get().playService
//                if (playService.isPlaying && playName == playService.playingMusic.title) {
//                    //点击了正在播放的这一曲
//                    sbProgress.setMax(playService.mediaPlayerTotalDuration.toFloat())
//                } else {
//                    playService.play(audioBean)
//                }
            }
        }

        override fun onServiceDisconnected(name: ComponentName) {

        }
    }
}